package auctionsimulation.market;

import java.util.HashMap;
import java.util.TimerTask;
import java.util.logging.Logger;

import auctionsimulation.agent.Agent;
import auctionsimulation.agent.SellAgent;
import auctionsimulation.statistics.Statistics;

public class ReverseEnglishAuction extends Auction {

	private static final long serialVersionUID = -456732791446994256L;

	private double currentPrice;
	private Agent currentLowestSeller;
	private long timeToWait;

	public ReverseEnglishAuction(SellAgent initiator,
			HashMap<String, Long> productTemplate, double price, long timeToWait) {
		super(initiator, productTemplate);
		this.currentLowestSeller = initiator;
		this.currentPrice = price;
		this.timeToWait = timeToWait;
		if (price <= 0)
			throw new IllegalAuctionException(
					"starting price of new reverse english auction must be positive");
		if (timeToWait <= 0)
			throw new IllegalAuctionException(
					"time to wait for new reverse english auction must be positive");
	}

	@Override
	public double getCurrentPrice() {
		return this.currentPrice;
	}

	public Agent getCurrentLowestSeller() {
		return this.currentLowestSeller;
	}

	public long getTimeToWait() {
		return this.timeToWait;
	}

	public synchronized boolean placePriceBid(Agent seller, double price,
			HashMap<String, Long> offeredTemplate) {
		if (started && !finished && price < currentPrice && price > 0
				&& this.checkNewOfferTemplateBetter(offeredTemplate)) {
			currentPrice = price;
			currentLowestSeller = seller;
			timer.schedule(new AuctionTask(), this.timeToWait);
			return true;
		}
		return false;
	}

	public synchronized boolean buy() {
		if (started && !finished) {
			finished = true;
			successfull = true;
			Statistics.successfullAuctions++;
			Statistics.successfullReverseEnglishAuctions++;
			timer.cancel();
			Logger.getGlobal().info("auction " + this + "ended successfully");
			return true;
		}
		return false;
	}

	@Override
	public synchronized void start() {
		if (!started) {
			timer.schedule(new AuctionTask(), this.timeToWait);
			started = true;
			Statistics.startedAuctions++;
			Statistics.startedReverseEnglishAuctions++;
			Logger.getGlobal().info("auction " + this + "has been started");
		}
	}

	private class AuctionTask extends TimerTask {

		@Override
		public void run() {
			if (!finished) {
				finished = true;
				Logger.getGlobal().info(
						"auction " + this + " ended unsuccessfully");
			}
		}
	}

}
